package com.dyh.quickdemozwei.beanReplace;


import groovy.lang.GroovyClassLoader;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/*
@Author=Joey Wheeler
@Date=2021/1/7 13:19
*/
@Component
public class BeanReplaceBiz implements ApplicationContextAware {

    private ApplicationContext ac;
    private static final GroovyClassLoader groovyClassLoader = new GroovyClassLoader();

    @Autowired
    private DefaultListableBeanFactory defaultListableBeanFactory;

    @Override
    public void setApplicationContext(ApplicationContext ac) throws BeansException {
        this.ac = ac;
    }

    public void replace(BeanReplace beanReplace) throws IllegalAccessException, InstantiationException {
        Class<?> clazz = groovyClassLoader.parseClass(beanReplace.getSource());
        Object newBean = clazz.newInstance();
        String beanName = beanReplace.getBeanName();
      //  Object oldBean = this.ac.getBean(beanName);
        AutowireCapableBeanFactory autowireCapableBeanFactory = this.ac.getAutowireCapableBeanFactory();
        defaultListableBeanFactory.removeBeanDefinition(beanName);

        defaultListableBeanFactory.registerBeanDefinition(beanName, BeanDefinitionBuilder.genericBeanDefinition(clazz).getBeanDefinition());
        //这里要手动注入新类里面的依赖关系
        autowireCapableBeanFactory.autowireBean(newBean);
    }





}
